<template>
    <div id="courseForum">
        <div class="Wangeditor-container">
            <div class="Wangeditor-avatar-container">
                <el-avatar size="large" :src="user?.headportrait" />
            </div>
            <Wangeditor class="WangeditorEL" ref="WangeditorEL"
                v-bind="{ menu, height, Toolbarshow, handleFocus, handleBlur, placeholder: '请输入内容...' }">
            </Wangeditor>
            <div class="submit-btn-container">
                <el-button size="default" type="primary" @click="submit">发表评论</el-button>
            </div>
        </div>
        <div>
            <el-container class="courseForum-container" v-for="(v, key) in getCourseForumData " :key="key">
                <el-aside class="avatar-container">
                    <el-avatar size="default" :src="v.headimage"></el-avatar>
                </el-aside>
                <el-main class="courseForum-content">
                    <header class="courseForum-content-header">
                        <div class="username">
                            {{ v.username }}
                        </div>
                        <div class="text-right" v-if="showDelEl(v.userid)">
                            <el-popover trigger="click" placement="top"
                                :popper-style="{ minWidth: 'auto', width: 'auto' }">
                                <el-button size="default" type="danger" plain
                                    @click="delCourseForum(v.ID)">删除</el-button>
                                <template #reference>
                                    <el-icon class="icon-MoreFilled">
                                        <MoreFilled />
                                    </el-icon>
                                </template>
                            </el-popover>
                        </div>
                    </header>
                    <div class="courseForum-content-context">
                        <el-scrollbar>
                            <div v-html="v.context" class="editor-content-view"></div>
                        </el-scrollbar>
                    </div>
                    <div class="">
                        <div class="courseForum-content-date font-size14">
                            <span v-text="TimeYH(v.createdAt)"></span>
                            <el-button size="default" type="primary" text bg @click="showReplyEl(key)">回复</el-button>
                        </div>
                        <el-collapse-transition>
                            <div class="courseForum-reply-input" v-show="inputkey === key">
                                <el-input size="default" :minlength="5" :placeholder="`回复:${v.username}`"
                                    v-model="input">
                                    <template #append>
                                        <el-button @click="reply(v.ID, input)">发表</el-button>
                                    </template>
                                </el-input>
                            </div>
                        </el-collapse-transition>
                    </div>
                    <el-container class="courseForum-children-container" v-for="( item, keys ) in v.children"
                        :key="`${key}-${keys}`">
                        <el-aside class="avatar-container">
                            <el-avatar size="default" :src="item.headimage"></el-avatar>
                        </el-aside>
                        <el-main class="courseForum-content">
                            <header class="courseForum-content-header">
                                <div class="username">
                                    {{ item.username }}
                                </div>
                                <div class="text-right" v-if="showDelEl(item.userid)">
                                    <el-popover trigger="click" placement="top"
                                        :popper-style="{ minWidth: 'auto', width: 'auto' }">
                                        <el-button size="default" type="danger" plain
                                            @click="delCourseForum(item.ID)">删除</el-button>
                                        <template #reference>
                                            <el-icon class="icon-MoreFilled">
                                                <MoreFilled />
                                            </el-icon>
                                        </template>
                                    </el-popover>
                                </div>
                            </header>
                            <div class="courseForum-content-context">
                                <el-scrollbar>
                                    <div class="editor-content-view" v-html="item.context"></div>
                                </el-scrollbar>
                            </div>
                            <div class="courseForum-content-date font-size14">
                                <span v-text="TimeYH(item.createdAt)"></span>
                            </div>
                        </el-main>
                    </el-container>
                </el-main>
            </el-container>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import highlight from 'highlight.js';
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncCreatedCourseForum, asyncDelCourseForum, asyncSelectCourseForum, asyncselectteamuser, } from "../../../api";
import { Storekey } from "../../../interface";
import Alymodel from "../../../mysql_interface/model";
import { TimeYH } from '../../../util/time';
import Wangeditor, { Emenu, IWangEditor } from "../../components/wangeditor.vue";

const p = defineProps<{
    course: Alymodel.IMcourse,
    courseGroup: Alymodel.CourseGroup,
}>()

const store = useStore(Storekey)
const route = useRoute()
const router = useRouter()
// 当前登录用户
const user = computed(() => {
    return store.state.user;
});
const teamId = computed(() => {
    return Number(user.value?.teamid);
});

const menu: Emenu = [
    "head", // 标题
    "fontSize", // 字号
    "fontName", // 字体
    "italic", // 斜体
    "strikeThrough", // 删除线
    "foreColor", // 文字颜色
    "backColor", // 背景颜色
    "link", // 插入链接
    "justify", // 对齐方式
    "quote", // 引用
    "emoticon", // 表情
    "image", // 插入图片
    "code", // 插入代码
    "undo", // 撤销
    "redo", // 重复
]
const input = ref('')
const inputkey = ref<number | null>(null)
const height = ref("72px")

const totalCount = ref(0)
const offset = ref(0)
const limit = ref(10)

const Toolbarshow = ref(false)
const f = ref(false)
onMounted(async () => {
    // console.log("courseForum props=>", p)
    setTimeout(() => {
        f.value = true
    }, 1000)
    // await start()
})
watch(() => p.course, start)
// watch(() => offset.value, start)

// 整合数据结构
const getCourseForumData = computed(() => {
    const data: Alymodel.IMcourseforum[] = []
    courseForumData.value.filter((e) => !e.courseforumid).forEach((v) => {
        const n = courseForumData.value.filter((e) => e.courseforumid === v.ID)
            .sort(
                (a, b) =>
                    new Date(a.createdAt || Date.now()).getTime() -
                    new Date(b.createdAt || Date.now()).getTime()
            );
        data.push({ ...v, children: n });
    });
    return data
})
const courseForumData = ref<Alymodel.IMcourseforum[]>([])
async function start() {
    try {
        // 团队成员
        const { rows: teamUserRows, count: teamUserCount } = await asyncselectteamuser({ teamid: teamId.value, })
        const userid = teamUserRows.map(e => e.userid)
        // 评论
        const { rows, count } = await asyncSelectCourseForum({
            courseid: p.course.ID,
            state: [1, 2],
            userid
        });
        totalCount.value = count;
        courseForumData.value = rows;
    } catch (e: any) {
        console.error(e);
    }
    nextTick(() => {
        highlight.highlightAll()
    })
}

const showDelEl = (uid: number) => {
    let show = false
    if (user.value?.type === "admin" || user.value?.ID === uid) {
        show = true
    }
    return show
}

function showReplyEl(key: number) {
    if (key === inputkey.value) {
        inputkey.value = null;
    } else {
        inputkey.value = key;
    }
}

const WangeditorEL = ref<IWangEditor>()
function handleFocus() {
    if (f.value) {
        height.value = "400px";
        Toolbarshow.value = true
    } else {
        WangeditorEL.value?.instance.blur()
    }
}
function handleBlur() {
    height.value = "50px";
    Toolbarshow.value = false
}

async function submit() {
    const editor: any = WangeditorEL.value;
    const text: string = editor.gettext();
    const html: string = editor.syncHTML();
    const htmlcontext: string = editor.getcontext();
    if (!text.length) {
        ElMessage.error("评论内容过少");
        return;
    }
    try {
        await asyncCreatedCourseForum({
            userid: user.value?.ID,
            courseid: p.course.ID,
            context: html,
            // 回复对象
            courseforumid: undefined,
            username: user.value?.name,
            headimage: user.value?.headportrait,
            userphonenum: String(user.value?.name) + "-" + user.value?.phonenum,
            catebag: p.courseGroup?.name || "",
            coursename: `[${p.course?.name || ''}](${location.href})`,
        });
        ElMessage.success("提交成功");
        editor.removeNodes();
    } catch (e: any) {
        ElMessage.error(e);
    }
    start();
}

async function reply(courseforumid: any, text: string) {
    if (!text.length) {
        ElMessage.error("评论内容过少");
        return;
    }
    if (!text && !courseforumid) return;
    try {
        await asyncCreatedCourseForum({
            userid: user.value?.ID,
            courseid: p.course.ID,
            context: text,
            // 回复对象
            courseforumid,
            username: user.value?.name,
            headimage: user.value?.headportrait,
            userphonenum: String(user.value?.name) + "-" + user.value?.phonenum,
            catebag: p.courseGroup?.name || "",
            coursename: `[${p.course?.name || ''}](${location.href})`,
        });
        ElMessage.success("提交成功");
        inputkey.value = null;
        input.value = "";
    } catch (e: any) {
        input.value = "";
        ElMessage.error(e);
    }
    start();
}

async function delCourseForum(ID: number | undefined) {
    ElMessageBox.confirm("是否删除该评论, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
    }).then(async () => {
        try {
            if (ID) {
                await asyncDelCourseForum({ ID });
                ElMessage.success("删除成功");
                start();
            }
        } catch (e: any) {
            ElMessage.error(e);
        }
    });
}

</script>

<style scoped>
.Wangeditor-container {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 0 var(--container-margin) var(--container-margin);
    border-bottom: 1px solid rgb(196, 196, 196);
}

.Wangeditor-avatar-container {
    width: 60px;
}

.WangeditorEL {
    flex: 1 0 0%;
    overflow: hidden;
    /* width: 90%; */
}

.submit-btn-container {
    text-align: right;
    width: 110px;
}

.courseForum-container {
    padding: var(--container-margin);
    /* margin-bottom: var(--container-margin); */
    border-bottom: 1px solid #dee2e6;
}

.avatar-container {
    width: 50px;
}

.courseForum-content {
    padding: 0 0 0 var(--container-margin);
}

.courseForum-content-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.username {
    font-weight: bolder;
    font-size: 14px;
    color: #8c8c8c;
    line-height: 24px;
}

.icon-MoreFilled {
    transform: rotate(90deg);
}

.courseForum-content-context {
    /* margin: 10px 0; */
    overflow: auto;
}

.editor-content-view {
    padding: 10px 0;
}

.courseForum-content-date {
    height: auto;
    display: flex;
    align-items: center;
}

.courseForum-content-date span {
    color: #8c8c8c;
    display: inline-block;
    margin-right: var(--container-margin);
}

.courseForum-reply-input {
    margin: 10px 0;
}

.courseForum-children-container {
    margin: 10px 0;
}
</style>

<style>
#courseForum p {
    margin-bottom: 0px;
}
</style>